<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2019/8/31
 * Time: 11:41
 */

declare (strict_types=1);

namespace app\service\traits;

use think\Response;

trait Unified
{
    private static $config;

    /**
     * 成功回调
     *
     * @param string $msg
     * @return string
     */
    private function success(string $msg = ''): string
    {
        return $msg ?: $msg = '请求成功';
    }

    /**
     * 失败回调
     *
     * @param int $code
     * @param mixed ...$msg
     * @return string
     */
    private function error(int $code, ...$msg): string
    {
        $message = getErrorMessage($code, self::getErrorConfig());

        return $msg ? sprintf($message, ...$msg) : $message;
    }

    /**
     * 返回数据
     *
     * @param int $code
     * @param string $msg
     * @param array $data
     * @return Response
     */
    protected function returnData(int $code, string $msg = '', array $data = []): Response
    {
        if ($code != 500) $msg = 200 == $code ? $this->success($msg) : $this->error($code, $msg);

        return json(echoArr($code, $msg, $data), 200);
    }

    /**
     * 获取错误配置
     *
     * @return array
     */
    protected static function getErrorConfig(): array
    {
        if (!self::$config) self::$config = array_merge(config('error'), ['common' => config('app.errorCode')]);

        return self::$config;
    }
}
